﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
#if NETFX_CORE
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
#else
using System.Windows;
#endif

namespace FreshMeat.Xaml
{
   public static class XamlHelper
   {
      public static string GetPath(DependencyObject o)
      {
         var chain = new List<DependencyObject>();
         GetInheritanceChain(chain, o);

         var builder = new StringBuilder();

         if (chain.Count >= 7) // Should be at least 3 more than the number being taken (remember we add the last one at the end)
         {
            foreach (var item in chain.Take(4))
               AddItem(builder, item);
            builder.Append(". . ");
            AddItem(builder, chain.Last());
         }
         else
         {
            foreach (var item in chain)
               AddItem(builder, item);
         }

         return builder.ToString();
      }

      static void AddItem(StringBuilder builder, DependencyObject o)
      {
         if (builder.Length > 0)
            builder.Append(".");

         AddItemName(builder, o);
      }

      static void AddItemName(StringBuilder builder, DependencyObject o)
      {
         builder.Append(o.GetType().Name);

         var frameworkElement = o as FrameworkElement;
         if (frameworkElement != null && !string.IsNullOrEmpty(frameworkElement.Name))
         {
            builder.Append('(');
            builder.Append(frameworkElement.Name);
            builder.Append(')');
         }
      }

      static void GetInheritanceChain(List<DependencyObject> chain, DependencyObject o)
      {
         if (o == null)
            return;

         var parent = LogicalTreeHelper.GetParent(o);
         GetInheritanceChain(chain, parent);

         chain.Add(o);
      }
   }
}
